<!-- src/views/product/shangpin/query.vue -->
<script setup>
import { ref, onMounted } from 'vue'
import {
  Search,
  RefreshRight,
  Upload
} from '@element-plus/icons-vue'
import api from '@/utils/request.js'
import { ElMessage } from 'element-plus'
import { formatDay } from '@/utils/date.js'

// 分页数据
const spuList = ref([])
const loading = ref(false)
const total = ref(0)

// 品牌选项列表 (key: 品牌ID, value: 品牌名称)
const brandList = ref({})

// 获取品牌列表
const getBrandList = async () => {
  try {
    const result = await api.get('tBrand/list')
    if (result.code === 200) {
      brandList.value = result.data
    }
  } catch (error) {
    ElMessage.error('获取品牌列表失败')
  }
}

// 级联选择器选项
const cascaderOptions = ref([])

// 级联选择器配置
const cascaderProps = {
  value: 'id',
  label: 'name',
  children: 'children',
  emitPath: true,
  checkStrictly: true
}

// 转换类型数据为级联选择器格式
const transformCategoryData = (data) => {
  if (!Array.isArray(data)) return []

  return data.map(item => {
    const option = {
      id: item.id,
      name: item.name
    }

    if (item.children && item.children.length > 0) {
      option.children = item.children.map(child => ({
        id: child.id,
        name: child.name
      }))
    }

    return option
  })
}

// 获取分类列表
const getTypeList = async () => {
  try {
    const result = await api.get('/tCategory/list1')
    if (result.code === 200) {
      cascaderOptions.value = transformCategoryData(result.data)
    }
  } catch (error) {
    ElMessage.error('获取类型列表失败')
  }
}

// 搜索时间范围
const searchTime = ref(["", ""])

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  name: '',           // 商品名称查询条件
  brandId: '',        // 品牌ID查询条件
  categoryId: '',     // 分类ID查询条件
  secondCategoryId: '', // 二级分类ID查询条件
  status: '',         // 状态查询条件
  startTime: '',      // 开始时间
  endTime: ''         // 结束时间
})

// 重置查询条件
const resetQueryForm = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    name: '',
    brandId: '',
    categoryId: '',
    secondCategoryId: '',
    status: '',
    startTime: '',
    endTime: ''
  }
  searchTime.value = ["", ""]
  getSpuList()
}

// 查询方法
const query = () => {
  if (searchTime.value[0] !== '') {
    queryParams.value.startTime = formatDay(searchTime.value[0])
    queryParams.value.endTime = formatDay(searchTime.value[1])
  }

  // 处理级联选择器的值
  if (Array.isArray(queryParams.value.categoryId)) {
    if (queryParams.value.categoryId.length === 1) {
      queryParams.value.categoryId = queryParams.value.categoryId[0]
      queryParams.value.secondCategoryId = ''
    } else if (queryParams.value.categoryId.length === 2) {
      const categoryIdArray = [...queryParams.value.categoryId];
      queryParams.value.categoryId = categoryIdArray[0];
      queryParams.value.secondCategoryId = categoryIdArray[1];
    } else {
      queryParams.value.categoryId = ''
      queryParams.value.secondCategoryId = ''
    }
  }

  getSpuList()
}

// 获取商品列表
const getSpuList = async () => {
  loading.value = true
  try {
    const result = await api.get('/tSpu/info', queryParams.value)
    spuList.value = result.data.list
    total.value = result.data.total
  } catch (error) {
    ElMessage.error('请求失败')
  } finally {
    loading.value = false
  }
}

// 分页相关方法
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val
  queryParams.value.pageNum = 1
  getSpuList()
}

const handleCurrentChange = (val) => {
  queryParams.value.pageNum = val
  getSpuList()
}

// 获取级联选择器节点标签
const getCascaderLabel = (targetId) => {
  if (!targetId || !cascaderOptions.value) return ''

  const findLabel = (nodes) => {
    for (const node of nodes) {
      if (node.id === targetId) {
        return node.name
      }
      if (node.children) {
        const found = findLabel(node.children)
        if (found) return found
      }
    }
    return ''
  }

  return findLabel(cascaderOptions.value)
}

// 计算完整类目名称
const getCategoryFullName = (row) => {
  if (row.categoryName && row.secondCategoryName) {
    return `${row.categoryName}/${row.secondCategoryName}`
  } else if (row.categoryName) {
    return row.categoryName
  } else if (row.secondCategoryName) {
    return row.secondCategoryName
  }
  return ''
}

// Excel导入成功回调
const uploadSuccess = () => {
  ElMessage.success("上传成功")
  query() // 刷新数据
}

// 初始化
onMounted(() => {
  getBrandList()
  getSpuList()
  getTypeList()
})
</script>

<template>
  <div class="app-container">
    <!-- 查询条件 -->
    <el-row>
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="编号/商品名">
          <el-input v-model="queryParams.name" clearable />
        </el-form-item>
        <el-form-item label="品牌">
          <el-select
              v-model="queryParams.brandId"
              placeholder="请选择品牌"
              clearable
          >
            <el-option
                v-for="(brandName, brandId) in brandList"
                :key="brandId"
                :label="brandName"
                :value="brandId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="类型">
          <el-cascader
              v-model="queryParams.categoryId"
              :options="cascaderOptions"
              :props="cascaderProps"
              placeholder="请选择类型"
              clearable
              style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
              v-model="queryParams.status"
              placeholder="状态"
              clearable
          >
            <el-option label="在售" value="1" />
            <el-option label="下架" value="2" />
            <el-option label="预售" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
              v-model="searchTime"
              type="daterange"
              unlink-panels
              range-separator="到"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="query">查询</el-button>
          <el-button type="primary" :icon="RefreshRight" @click="resetQueryForm">重置</el-button>
          <!-- 同步按钮 - Excel导入 -->
          <el-upload
              action="/admin-dev-api/tSpu/import/excel"
              :auto-upload="true"
              :on-success="uploadSuccess"
              :on-error="handleUploadError"
              :show-file-list="false"
              :limit="1"
              accept=".xls,.xlsx"    style="display: inline-block; margin-left: 10px;"
          >
            <template #trigger>
              <el-button type="success" :icon="Upload">同步</el-button>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
    </el-row>

    <!-- 数据表格 -->
    <el-row>
      <el-table
          v-loading="loading"
          :data="spuList"
          border
          stripe
          style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="spuNo" label="商品编号" width="120" />
        <el-table-column prop="spuName" label="商品名称" show-overflow-tooltip />
        <el-table-column prop="categoryName" label="类型" width="150">
          <template #default="scope">
            {{ getCategoryFullName(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column prop="brandName" label="品牌" width="100" />
        <el-table-column prop="unit" label="计量单位" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 1" type="success">在售</el-tag>
            <el-tag v-else-if="scope.row.status === 2" type="warning">下架</el-tag>
            <el-tag v-else-if="scope.row.status === 3" type="info">预售</el-tag>
            <span v-else>{{ scope.row.status }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createdTime" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDay(scope.row.createdTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="updatedTime" label="更新时间" width="180">
          <template #default="scope">
            {{ formatDay(scope.row.updatedTime) }}
          </template>
        </el-table-column>
      </el-table>
    </el-row>

    <!-- 分页 -->
    <el-row>
      <el-col :span="24">
        <el-pagination
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </el-col>
    </el-row>
  </div>
</template>

<style scoped>
.demo-form-inline {
  margin-bottom: 20px;
}
</style>
